﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Printing;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

namespace CloudDcPc.Util
{
    class PrintUtil
    {
        private IPEndPoint ServerInfo;
        private Socket ClientSocket;
        private Font printFont;

        public PrintUtil()
        {
            ClientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            ServerInfo = new IPEndPoint(IPAddress.Parse(Properties.Settings.Default.save_printer_ip), Convert.ToInt32("9100")); 
        }
        public void IpPrintString(string str)
        {
            ClientSocket.Connect(ServerInfo);
            byte[] b = System.Text.Encoding.GetEncoding("GB2312").GetBytes(str);

            ClientSocket.Send(b);

            byte[] cut = new byte[4] { 0x1d, 0x56, 0x00, 0x48 };  //半切纸
            ClientSocket.Send(cut);

            ClientSocket.Close();
        }
        /// <summary>
        /// usb打印机打印，打印机名为XP-80
        /// </summary>
        /// <param name="str">要打印的字符串</param>
        /// <param name="fontSize">字体大小10f感觉可以</param>
        public void UsbPrintString(string str)
        {
            printFont = new Font("宋体", 10f);
            PrintDocument pd = new PrintDocument();
            pd.PrintController = new System.Drawing.Printing.StandardPrintController();    //取消打印页码显示对话框！ 

            pd.PrintPage += delegate(object sender, PrintPageEventArgs e)
            {
                // float leftMargin = e.MarginBounds.Left - 10;//左边距

                e.Graphics.DrawString(str, printFont, System.Drawing.Brushes.Black,
                0, 0, new StringFormat());
            };

            pd.PrinterSettings.PrinterName = "XP-80";
            pd.Print();
        }
        public void UsbPrintStringTitle(string str)
        {
            printFont = new Font("微软雅黑", 13f);
            PrintDocument pd = new PrintDocument();
            pd.PrintController = new System.Drawing.Printing.StandardPrintController();    //取消打印页码显示对话框！ 

            pd.PrintPage += delegate(object sender, PrintPageEventArgs e)
            {
                e.Graphics.DrawString(str, printFont, System.Drawing.Brushes.Black,
                55, 0, new StringFormat());
            };

            pd.PrinterSettings.PrinterName = "XP-80";
            pd.Print();
        }

    }
}
